"""
API 依赖注入
"""
from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
# pyright: reportMissingImports=false
from sqlalchemy.ext.asyncio import AsyncSession 

from  core.database import get_db
from  core.security import decode_access_token
from  models.doctor import Doctor
from  crud import doctor as crud_doctor

# 定义安全scheme（显示Swagger UI的Authorize按钮）
security = HTTPBearer()


async def get_current_doctor(
    db: AsyncSession = Depends(get_db),
    credentials: HTTPAuthorizationCredentials = Depends(security)
) -> Doctor:
    """
    获取当前登录的医生
    使用 HTTPBearer 以在 Swagger UI 中显示 Authorize 按钮
    
    Args:
        db: 数据库会话
        credentials: HTTP Bearer 认证凭据
    
    Returns:
        当前医生对象
    
    Raises:
        HTTPException: 如果token无效或医生不存在
    """
    # 提取 token
    token = credentials.credentials
    
    print(f"[DEBUG] Token received: {token[:20]}..." if len(token) > 20 else f"[DEBUG] Token: {token}")
    
    # 解码token
    try:
        payload = decode_access_token(token)
        doctor_id_str: Optional[str] = payload.get("sub")
        
        # 将字符串 ID 转换为整数（JWT 标准要求 sub 必须是字符串）
        if doctor_id_str:
            try:
                doctor_id = int(doctor_id_str)
            except ValueError:
                doctor_id = None
        else:
            doctor_id = None
            
    except HTTPException:
        # 让 HTTPException 直接抛出，不要重新包装
        raise
    except Exception as e:
        print(f"[DEBUG] Token decode error: {e}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"Token解码失败: {str(e)}",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    if doctor_id is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证凭据",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    print(f"[DEBUG] Doctor ID from token: {doctor_id}")
    
    # 查询医生
    doctor = await crud_doctor.get(db, id=doctor_id)
    if not doctor:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="医生不存在",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 检查医生状态
    if doctor.status != 1:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="账号已被禁用",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    print(f"[DEBUG] Doctor authenticated: {doctor.name}")
    return doctor


async def get_current_active_doctor(
    current_doctor: Doctor = Depends(get_current_doctor)
) -> Doctor:
    """
    获取当前激活的医生
    
    Args:
        current_doctor: 当前医生
    
    Returns:
        当前医生对象
    """
    return current_doctor
